package com.hystrix.payment.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author：Administrator
 * @Date：2022/7/13/0013 19:35
 * @Versiion：1.0
 */
@Service
public class PaymentService {

    @Value("${server.port}")
    private int port;

    public String paymentOk(){
        return " payment ok port:" + port;
    }


    /*熔断的策略  超时或者异常都会走熔断处理函数*/
    @HystrixCommand(fallbackMethod = "paymentTimeout_handler",commandProperties = {
            /*设置个超时时间*/
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String paymentTimeout(){
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return " payment timeout port:" + port;
    }
    /**
     * paymentTimeout 的熔断处理
     * @return
     */
    public String paymentTimeout_handler(){
        return "服务咱不可用  请稍后再试";
    }



    /*熔断开关有三种状态：open => close => half open*/
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            //开启断路器
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            //请求次数
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            //时间窗口期 单位是ms
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
            //失败率标准 60%
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")
    })
    public String paymentCircuitBreaker(@PathVariable("id") int id){
        if(id<0){
            //这里抛出异常 走到下面的fallback中去
            throw new RuntimeException("--->>> ID 不能是负数");
        }
        return "测试熔断>"+ UUID.randomUUID().toString() + "   "+id;
    }

    public String paymentCircuitBreaker_fallback(int id){
        return "服务暂不可用 稍后再试!";
    }
}
